import request from "./index"
export const getAuditReport = async (companyName) => {
  return await request.get(`/api/audit-report/company/${companyName}`)
}

export const sendChatMessage = async (data) => {
  return await request.post("/api/chat/stream", data)
}

// 使用Fetch API代替
const url = "http://110.40.83.188:8825/api/chat/stream"
export async function sseWithPost(data, callback) {
  try {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "text/event-stream"
      },
      body: JSON.stringify(data)
    })

    if (!response.ok || !response.body) {
      throw new Error(`SSE connection failed: ${response.status}`)
    }

    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    let buffer = ""
    let event = {
      type: "message", // 默认事件类型
      data: "",
      id: null,
      retry: null
    }

    while (true) {
      const { done, value } = await reader.read()
      if (done) {
        // 处理缓冲区中剩余的数据
        if (buffer.length > 0) {
          processBuffer(buffer, event, callback)
        }
        break
      }

      buffer += decoder.decode(value, { stream: true })

      // 处理完整的事件（以\n\n分隔）
      while (buffer.includes("\n\n")) {
        const eventEndIndex = buffer.indexOf("\n\n")
        const eventData = buffer.substring(0, eventEndIndex)
        buffer = buffer.substring(eventEndIndex + 2)

        processEvent(eventData, event, callback)
      }
    }
  } catch (error) {
    console.error("SSE Error:", error)
    throw error
  }
}

// 处理单个SSE事件
function processEvent(eventData, currentEvent, callback) {
  // 重置事件对象，但保留一些默认值
  currentEvent.data = ""

  eventData.split("\n").forEach((line) => {
    if (line.startsWith("event:")) {
      currentEvent.type = line.replace("event:", "").trim()
    } else if (line.startsWith("data:")) {
      currentEvent.data += line.replace("data:", "").trim() + "\n"
    } else if (line.startsWith("id:")) {
      currentEvent.id = line.replace("id:", "").trim()
    } else if (line.startsWith("retry:")) {
      currentEvent.retry = parseInt(line.replace("retry:", "").trim())
    }
  })

  // 清理data末尾的换行符
  if (currentEvent.data) {
    currentEvent.data = currentEvent.data.trim()
  }

  // 调用回调函数，传递完整的事件对象
  if (callback && currentEvent.data) {
    try {
      // 尝试解析JSON数据
      const parsedData = JSON.parse(currentEvent.data)
      callback({
        type: currentEvent.type,
        data: parsedData,
        raw: currentEvent.data,
        id: currentEvent.id,
        retry: currentEvent.retry
      })
      // eslint-disable-next-line no-unused-vars
    } catch (e) {
      // 不是JSON数据，返回原始字符串
      callback({
        type: currentEvent.type,
        data: currentEvent.data,
        raw: currentEvent.data,
        id: currentEvent.id,
        retry: currentEvent.retry
      })
    }
  }
}

// 处理缓冲区中的数据
function processBuffer(buffer, currentEvent, callback) {
  const lines = buffer.split("\n")
  let eventData = ""

  lines.forEach((line) => {
    if (line === "") {
      // 空行表示事件结束
      if (eventData) {
        processEvent(eventData, currentEvent, callback)
        eventData = ""
      }
    } else {
      eventData += line + "\n"
    }
  })

  // 处理最后一个不完整的事件
  if (eventData) {
    processEvent(eventData, currentEvent, callback)
  }
}

export const generateReport = async (companyName) => {
  await request.post(`/api/audit-report/generate`, null, {
    params: {
      companyName
    }
  })
}

export const getCompanyList = async () => {
  return await request.get("/api/audit/problems/companies")
}

// 获取专业画像数据
export const getProfessionalReport = async (companyName) => {
  return await request.get(`/api/company/material-audit-profile/${companyName}`)
}
// 获取公司审计画像数据
export const getCompanyAudit = async (companyName) => {
  return await request.get(`/api/company/profile/query/${companyName}`)
}

// 获取公司对比信息
export const getCompareInfo = async (companyNameA, companyNameB) => {
  return await request.get(
    `/api/company/profile/compare?companyNameA=${companyNameA}&companyNameB=${companyNameB}`
  )
}
